package com.dh.modules.system.service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.dh.modules.system.dao.AdminToken;
import com.dh.common.utils.CharUtil;

public class AdminTokenManager {
    private static Map<String, AdminToken> tokenMap = new HashMap<>();
    private static Map<String, AdminToken> idMap = new HashMap<>();

    public static String getUserId(String token) {

        AdminToken userToken = tokenMap.get(token);
        if(userToken == null){
            return null;
        }

        if(userToken.getExpireTime().isBefore(LocalDateTime.now())){
            tokenMap.remove(token);
            idMap.remove(userToken.getUserId());
            return null;
        }

        return userToken.getUserId();
    }


    public static AdminToken generateToken(String id){
        AdminToken userToken = null;

        /**
         * 后登陆强迫让之前登录的下线
         */
        userToken = idMap.get(id);
        if(userToken != null) {
            tokenMap.remove(userToken.getToken());
            idMap.remove(id);
        }

        String token = CharUtil.getRandomString(32);
        while (tokenMap.containsKey(token)) {
            token = CharUtil.getRandomString(32);
        }

        LocalDateTime update = LocalDateTime.now();
        LocalDateTime expire = update.plusDays(1);

        userToken = new AdminToken();
        userToken.setToken(token);
        userToken.setUpdateTime(update);
        userToken.setExpireTime(expire);
        userToken.setUserId(id);
        tokenMap.put(token, userToken);
        idMap.put(id, userToken);

        return userToken;
    }

    public static void removeToken(String token) {
    	if(tokenMap.containsKey(token)) {
    		tokenMap.remove(token);
    	}
    }

    public static boolean removeIdToken(String userId) {
    	if(idMap.containsKey(userId)) {
    		String token = idMap.get(userId).getToken();
    		if(StringUtils.isNotBlank(token)) {
    			removeToken(token);
    		}
    		idMap.remove(userId);
    	}else {
    		return false;
    	}
    	return true;
    }

}
